<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php



 
class LoggerHierarchy {
	
	protected $defaultFactory;
	
	
	protected $ht = array();
	
	
	protected $root = null;
	
	
	protected $rendererMap;

	
	protected $threshold;
	
	
	public function __construct(LoggerRoot $root) {
		$this->root = $root;
		$this->setThreshold(LoggerLevel::getLevelAll());
		$this->rendererMap = new LoggerRendererMap();
	}
	 
	
	public function clear() {
		$this->ht = array();
	}
	
	
	public function exists($name) {
		return isset($this->ht[$name]);
	}

		 
	public function getCurrentLoggers() {
		return array_values($this->ht);
	}
	
	
	public function getLogger($name) {
		if(!isset($this->ht[$name])) {
			$this->ht[$name] = new Logger($name);;
									$nodes = explode('.', $name);
			$firstNode = array_shift($nodes);
			
						if($firstNode != $name and isset($this->ht[$firstNode])) {
				$this->ht[$name]->setParent($this->ht[$firstNode]);
			} else {
								$this->ht[$name]->setParent($this->root);
			} 
		
						if(count($nodes) > 0) {
								foreach($nodes as $node) {
					$parentNode = "$firstNode.$node";
					if(isset($this->ht[$parentNode]) and $parentNode != $name) {
		
						$this->ht[$name]->setParent($this->ht[$parentNode]);
					}
					$firstNode .= ".$node";
				}
			}
		}		
		
		return $this->ht[$name];
	} 
	
	
	public function getRendererMap() {
		return $this->rendererMap;
	}
	
	 
	public function getRootLogger() {
		if(!isset($this->root) or $this->root == null) {
			$this->root = new LoggerRoot();
		}
		return $this->root;
	}
	 
	
	public function getThreshold() {
		return $this->threshold;
	} 

	
	public function isDisabled(LoggerLevel $level) {
		return ($this->threshold->toInt() > $level->toInt());
	}
	
	
	public function resetConfiguration() {
		$root = $this->getRootLogger();
		
		$root->setLevel(LoggerLevel::getLevelDebug());
		$this->setThreshold(LoggerLevel::getLevelAll());
		$this->shutDown();
		$loggers = $this->getCurrentLoggers();
		$enumLoggers = count($loggers);
		for($i = 0; $i < $enumLoggers; $i++) {
			$loggers[$i]->setLevel(null);
			$loggers[$i]->setAdditivity(true);
			$loggers[$i]->removeAllAppenders();
		}
		$this->rendererMap->clear();
		LoggerAppenderPool::clear();
	}
	
	
	public function setThreshold(LoggerLevel $l) {
		if($l !== null) {
			$this->threshold = $l;
		}
	}
	
	
	public function shutdown() {
		$this->root->removeAllAppenders();
		$cats = $this->getCurrentLoggers();
		$enumCats = count($cats);
		if($enumCats > 0) {
			for($i = 0; $i < $enumCats; $i++) {
				$cats[$i]->removeAllAppenders();
			}
		}
	}
} 
